using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Collections.Concurrent;
using Weight.Base;

namespace  RFCard
{

 /// <summary>
 /// Summary:ID卡设备读卡类(近距)
 /// author:LYF
 /// DateTime 2019-01-28
 /// </summary>
    public class IDDeviceN: ICard
    {
        /// <summary>
        /// 串口对象
        /// </summary>
        private SerialPort mPort;

        /// <summary>
        /// 卡号对象
        /// </summary>
        private IDVaEntity mCarNoEntity;

        /// <summary>
        ///卡号比对集合
        /// </summary>
        private List<string> mComparison = null;

        /// <summary>
        /// 初始化
        /// </summary>
        /// <returns></returns>
        public ResultEntity Init()
        {
            var result = ResultEntity.Default();
            try
            {
                if(mPort != null && mPort.IsOpen)
                {
                    mPort.Close();
                }
                mPort = new SerialPort();
                mPort.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(this.serialPort1_DataReceived);
                mCarNoEntity = new IDVaEntity();
                result = ResultEntity.Success("ID卡设备初始化成功!");
            }
            catch(Exception ex)
            {
                result = ResultEntity.Error("ID卡设备初始化异常,异常信息:"+ex.Message+","+ex.StackTrace);
            }

            return result;
        }

        /// <summary>
        /// 读取数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            try
            {
                string value = mPort.ReadLine();
                value = filterDigit(value);
                value = getJHID2(value);
                mCarNoEntity.IDNo = value;
                mCarNoEntity.Time = DateTime.Now;
            }
            catch (Exception ex)
            {
            }
        }
            /// <summary>
            /// 初始化
            /// </summary>
            /// <param name="entity"></param>
            /// <returns></returns>
        public ResultEntity Open(OpenEntity entity)
        {
            var result = ResultEntity.Default();
            try
            {
                if(mPort.IsOpen)
                {
                    mPort.Close();
                }
                mPort.PortName = "COM" + entity.Port;
                mPort.BaudRate = entity.BaudRate;
                mPort.Open();
               if( mPort.IsOpen)
               {
                    result = ResultEntity.Success("ID卡设备 打开成功!");
               }
               else
               {
                    result = ResultEntity.Error("ID卡设备 打开失败!");
                }
            }
            catch(Exception ex)
            {
                result = ResultEntity.Error("ID卡设备打开异常,异常信息:"+ex.Message+","+ex.StackTrace);
            }

            return result;
        }

        /// <summary>
        /// 获取卡号
        /// </summary>
        /// <returns></returns>
        public ResultEntity<ResultValEntity> GetCardNo()
        {
            ResultValEntity entity = new ResultValEntity();
            var result = ResultEntity< ResultValEntity>.Default(entity,"");
            try
            {
                if (DateTime.Now.Subtract(mCarNoEntity.Time).TotalSeconds <= 2)
                {
                    entity.val = getLimitCarNo(mCarNoEntity.IDNo);
                    result = ResultEntity<ResultValEntity>.Success(entity, entity.val);
                }
                else
                {
                    entity.val = "";
                    result = ResultEntity<ResultValEntity>.Success(entity, "卡片不存在");
                }
            }
            catch(Exception ex)
            {
                result = ResultEntity<ResultValEntity>.Error(entity,"ID卡设备打开异常，异常信息:"+ex.Message+","+ex.StackTrace);
            }

            return result;
        }


        /// <summary>
        /// 读取存储区内容
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public ResultEntity<ResultValEntity> Read(ReadParamEntity entity)
        {
            ResultValEntity valEntity = new ResultValEntity() {
                val = "该读卡设备不支持该方法！"
            };
            return ResultEntity<ResultValEntity>.Success(valEntity,"ID卡设备不支持该功能");
        }

        /// <summary>
        /// 写卡
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public ResultEntity Write(WriteParamEntity entity)
        {
            return ResultEntity.Success("ID卡设备不支持该功能");
        }


       /// <summary>
       /// 获取比对
       /// </summary>
       /// <param name="cardNos"></param>
        public void SetComparison(List<string> cardNos)
        {
            mComparison = cardNos;
        }

        /// <summary>
        ///清空
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public ResultEntity Clear(ClearParamEntity entity)
        {
            return ResultEntity.Success("ID卡设备不支持该功能");
        }

        /// <summary>
        /// 关闭
        /// </summary>
        /// <returns></returns>
        public ResultEntity Close()
        {
            var result = ResultEntity.Default();
            try
            {
                if (mPort != null && mPort.IsOpen)
                {
                    mPort.Close();
                    if(!mPort.IsOpen)
                    {
                        result = ResultEntity.Success("ID卡设备关闭成功");
                    }
                    else
                    {
                        result = ResultEntity.Error("ID卡设备关闭失败");
                    }
                }
                else
                {
                    result = ResultEntity.Success("ID卡设备非打开状态，无需关闭!");
                }
            }
            catch(Exception ex)
            {
                result = ResultEntity.Error("ID卡设备异常，异常消息:"+ex.Message+","+ex.StackTrace);
            }

            return result;
        }

        /// <summary>
        /// 获取设备信息
        /// </summary>
        /// <returns></returns>
        public ResultEntity GetDeviceInfo()
        {
            throw new NotImplementedException();
        }

        /// <summary>
        ///过滤
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        private string filterDigit(string value)
        {
            StringBuilder buider = new StringBuilder();
            for (int index = 0; index < value.Length; index++)
            {
                char ch = value[index];
                if (ch >= '0' && ch <= '9')
                {
                    buider.Append(ch);
                }
            }
            return buider.ToString(); ;
        }

        /// <summary>
        /// 返回匹配卡号
        /// </summary>
        /// <param name="cardNo">ID卡号</param>
        /// <returns></returns>
        private string getLimitCarNo(string cardNo)
        {
            if (mComparison != null && mComparison.Count > 0 && cardNo.Length > 0)
            {
                if (mComparison.Contains(cardNo))
                {
                    return cardNo;
                }
                else
                {
                    return "非匹配卡号";
                }
            }
            else
            {
                return cardNo;
            }
        }


        /// <summary>
        /// 远距离ID卡的特殊处理
        /// </summary>
        /// <param name="ls_str"></param>
        /// <returns></returns>
        public static string getJHID2(string ls_str)
        {
            string ls_idhex = ls_str;
            ls_idhex = ls_idhex.Substring(2, ls_idhex.Length - 2);
            long id = Convert.ToInt64(ls_idhex, 16);
            ls_idhex = id.ToString("D10");
            return ls_idhex;
        }
    }
}


